package com.fh.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fh.common.ResultEnum;
import com.fh.common.ResultMessage;
import com.fh.config.AlipayConfig;
import com.fh.util.DateUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@CrossOrigin
@RestController
@RequestMapping("alipay")
public class PayController {
    @RequestMapping("alipayOpen")
    public ResultMessage alipayOpen(BigDecimal totalPrice) throws AlipayApiException {
        AlipayClient alipayClient=new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(String.valueOf(DateUtil.getNumberId()));
        //付款金额，必填
        String total_amount = new String(String.valueOf(totalPrice));
        //订单名称，必填
        String subject = new String("你正在购买奥里给产品，请立即支付！！！");

        String time_express="lc";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"time_express\":\""+ time_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求

        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return new  ResultMessage(ResultEnum.PAY_SUCCESS,result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return new  ResultMessage(ResultEnum.PAY_ERROR);
        }
    }
}
